<template>
  <div class="login">
    <div class="top_body"></div>
    <div class="header-login">
      <div class="login-log">
        <img class="logo" src="@/assets/img/logo.png" alt="" />
      </div>
    </div>
    <div class="body-bg">
      <div class="login-main">
        <h2 class="site-title">登录账号</h2>
        <el-form
          ref="login"
          :model="login"
          size="medium"
          :rules="loginRules"
          class="login-form"
          label-position="left"
        >
          <el-form-item class="input_bottom" prop="account">
            <el-input
              v-model="login.account"
              type="text"
              placeholder="用户名"
              prefix-icon="el-icon-user"
              autocomplete="off"
              clearable
            />
          </el-form-item>
          <el-form-item class="input_bottom" prop="password">
            <el-input
              v-model="login.password"
              type="text"
              placeholder="密码"
              prefix-icon="el-icon-lock"
              @keyup.enter.native="handleLogin"
              autocomplete="off"
              clearable
              show-password
            />
          </el-form-item>
          <el-form-item class="input_bottom" prop="verify" v-if="verify_status">
            <el-col :span="13">
              <el-input
                v-model="login.verify"
                type="text"
                placeholder="验证码"
                prefix-icon="el-icon-picture"
                @keyup.enter.native="handleLogin"
                autocomplete="off"
                clearable
              />
            </el-col>
            <el-col :span="11">
              <el-image
                :src="verifySrc"
                alt="验证码"
                title="点击刷新验证码"
                @click="refeshVerifySrc"
                class="verifySrc"
              />
            </el-col>
          </el-form-item>
        </el-form>
        <el-button
          class="login_load"
          :loading="loading"
          size="medium"
          round
          type="primary"
          @click.native.prevent="handleLogin"
        >
          <span v-if="!loading">登 录</span>
          <span v-else>登 录 中...</span>
        </el-button>
      </div>
    </div>
    <div class="footer-login">
      版权所有©深圳市和兴国际货运代理有限公司
      <a href="https://beian.miit.gov.cn">粤ICP备20061134号</a>
    </div>
  </div>
</template>

<script>
import { reqVerifyApi } from "@/api/index";
import { getToken, setClientId } from "@/utils/auth";
import { mapActions, mapMutations, mapState } from "vuex";
import { bindMembeId } from "@/api/index";
import socketMixins from "@/socket/sockerMixins";

export default {
  mixins: [socketMixins],
  data() {
    return {
      loading: false,
      login: {
        account: "",
        password: "",
        rememberMe: false,
      },
      // client_id:undefined, // 携带client_id登录
      loginRules: {
        account: [{ required: true, message: "请输入用户名", trigger: "blur" }],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
        verify: [{ required: true, message: "请输入验证码", trigger: "blur" }],
      },
      verifySrc: "",
      verify_status: true,
      ws: void 0, // ws链接
    };
  },
  created() {
    // // 创建客户端的WebSocket对象并保存client_id
    // this.conn();
    this.$message({
      message: "请输入账号和密码",
      type: "warning",
    });
    this.$store.commit("tags/clearTags");
    localStorage.removeItem("erabbit-client-pc-store");
  },
  mounted() {
    this.captch();
  },

  // beforeDestroy() {
  // },
  computed: {
    ...mapState("user", {
      membe_token: (state) => state.token,
    }),
  },

  methods: {
    ...mapMutations("user", ["setWs"]),
    //发送消息
    // send() {
    //   this.ws.send();
    // },
    // 发起scoket链接
    conn() {
      const that = this;
      let wsURL =
        process.env.NODE_ENV == "development"
          ? "ws://worker.e-kc.com:2348"
          : "wss://worker.e-kc.vip:2348";

      this.ws = new WebSocket(wsURL);
      this.setWs(this.ws);
      //连接成功建立的回调方法
      this.ws.onopen = function () {
        console.log("index连接成功");
      };
      //   接收信息
      this.ws.onmessage = async function (message) {
        if (JSON.parse(message.data).client_id) {
          // that.client_id = JSON.parse(message.data).client_id
          setClientId({ client_id: JSON.parse(message.data).client_id });
          if (getToken()) {
            await bindMembeId({
              client_id: JSON.parse(message.data).client_id,
            });
          }
        }
        //   不同的类型执行不同的操作
        //   console.log(JSON.parse(message.data).type)
        switch (JSON.parse(message.data).notice_type) {
          case "cp_shop":
            that.showNotify(JSON.parse(message.data));
            break;
          case "news":
            that.showMessage(JSON.parse(message.data));
            break;
          case "system":
            that.showSystem(JSON.parse(message.data));
            break;
          case "order":
            that.submitData(JSON.parse(message.data));
            break;
          case "order_error":
            that.resultData(JSON.parse(message.data));
            break;
          case "order_enter":
            that.resultData(JSON.parse(message.data));
            break;
          case "up_cp_product":
            that.submitData(JSON.parse(message.data));
            break;
          case "cp_product_enter":
            that.resultData(JSON.parse(message.data));
            break;
        }
      };

      //连接发生错误的回调方法
      this.ws.onerror = function () {
        console.log("WebSocket连接发生错误");
      };
      //发送信息
      this.ws.send = function () {
        console.log("像服务端发送信息");
      };
      //连接关闭的回调方法、退出登录的时候再销毁
      this.ws.onclose = function () {
        console.log("WebSocket连接关闭index");
      };
    },
    //辅助函数
    ...mapActions({
      getToken: "user/getToken",
    }),

    //验证码
    async captch() {
      const res = await reqVerifyApi();
      this.verifySrc = res.data.data.img;
      this.login.key = res.data.data.key;
    },
    refeshVerifySrc() {
      this.captch();
    },
    handleLogin() {
      const that = this;
      this.$refs["login"].validate(async (valid) => {
        if (valid) {
          this.loading = true;
          try {
            const res = await this.getToken(this.login);
            if (res.status === 200) {
              this.loading = false;
              this.$router.push("/home");
              this.$message({
                message: "登录成功",
                type: "success",
              });
              // 创建客户端的WebSocket对象并保存client_id
              that.conn();
            } else {
              this.loading = false;
              this.refeshVerifySrc();
              this.$message({
                message: res.msg,
                type: "error",
              });
            }
          } catch (error) {
            this.loading = false;
            this.refeshVerifySrc();
            this.$message({
              message: "系统错误",
              type: "error",
            });
          }
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.login {
  width: 100%;
  height: 100%;

  .top_body {
    height: 50px;
  }

  .body-bg {
    position: absolute;
    margin: auto;
    height: 600px;
    width: 100%;
    top: 150px;
    left: 0;
    overflow-y: auto;
    background: url(../../assets/img/bg-image.jpg) top center;
    align-items: center;
    background-size: cover;

    .login-main {
      /*z-index: 1;*/
      background-color: #fff;
      border-radius: 20px;
      border: 1px solid #fff;
      width: 320px;
      height: 280px;
      position: absolute;
      left: 70%;
      top: 50%;
      transform: translate(-50%, -50%);
      padding: 20px;

      .site-title {
        font-weight: bold;
        font-size: 20px;
        text-align: center;
        color: #707070;
        margin-bottom: 21px;
      }

      .verifySrc {
        width: 108px;
        height: 35px;
        margin-top: 3px;
        float: right;
      }

      .login-form {
        .input_bottom {
          margin-bottom: 18px;
        }
      }

      .login_load {
        width: 100%;
      }
    }
  }

  .header-login {
    display: flex;
    justify-content: flex-start;
    align-items: center;

    .login-log {
      margin-left: 50px;

      .logo {
        width: 185px;
        height: 50px;
      }
    }
  }

  .footer-login {
    position: fixed;
    bottom: 10px;
    left: 50%;
    transform: translateX(-50%);
    color: #666;
    text-align: center;
    font-size: 20px;

    a {
      color: #666;
    }
  }
}
</style>
